package v1

import (
	"backend/pkg/e"
	"backend/pkg/logging"
	"backend/pkg/upload"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
)

func UploadFile(c *gin.Context) {
	code := e.SUCCESS
	data := make(map[string]string)

	file, err := c.FormFile("file")
	if err != nil {
		logging.Warn(err)
		code = e.ERROR
		c.JSON(http.StatusBadRequest, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": data,
		})
		return
	}

	filename := filepath.Join(upload.GetTempPath(), filepath.Base(file.Filename))

	if err := c.SaveUploadedFile(file, filename); err != nil {
		logging.Warn(err)
		code = e.ERROR_UPLOAD_SAVE_IMAGE_FAIL
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": data,
		})
		return
	}

	uniqueName, err := upload.SaveFile(filename)
	if err != nil {
		logging.Warn(err)
		code = e.ERROR
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": data,
		})
		return
	}
	err = os.Remove(filename)
	if err != nil {
		logging.Warn(err)
		code = e.ERROR
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": data,
		})
		return
	}

	data["image_url"] = upload.GetFileFullUrl(uniqueName)
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
